package com.lhm.controller;


import com.lhm.entity.Hot;
import com.lhm.entity.LargeFile;
import com.lhm.service.HotService;
import com.lhm.service.LargeFileService;
import com.lhm.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

//@CrossOrigin
@RestController
@RequestMapping("/api/adm/hot")
//热点
public class HotController {
    @Autowired
    HotService hotService;
    @Autowired
    LargeFileService largeFile1Service;

    //添加
    @RequestMapping("/addHot")
    public Map<String,Object>addHot(Hot hot, @RequestParam("pic")
            MultipartFile file)throws Exception{
        LargeFile largefile = new LargeFile();
        if(file!=null&&file.getSize()>0){
            largefile.setFilename(file.getOriginalFilename());
            String uuid=UUID.randomUUID().toString();
            largefile.setId(uuid);
            byte[] buf = file.getBytes();
            largefile.setContent(buf);
        }
        if(largefile.getId()!=null){
            hot.setPicture(largefile.getId());
            largeFile1Service.addLargefile(largefile);

        }
        hotService.addHot(hot);
        return RespJson.pack(200, "添加成功",hot);
    }
    //查找全部
    @RequestMapping("/findAll")
    public Map<String,Object> findAll(){
        List<Hot> lst = hotService.findAll();
        return RespJson.pack(200,"ok",lst);
    }

    //删除
    @RequestMapping({"/delete/{id}"})
    public Map<String, Object> delete(@PathVariable Integer id) {
        Hot hot = hotService.findById(id);      //根据id找到hot的pic
        System.out.println(hot.getPicture());
        String picture = hot.getPicture();
        largeFile1Service.delete(picture);      //根据pic 删除图片
        int i = hotService.delete(id);
        System.out.println(i);
        return RespJson.pack(200, "删除成功...", null);
    }

    /**
     * 自动转换日期类型的字段格式
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }

}
